// pages/registered/registered.js
const app = getApp();
const phoneRexp = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    form_name_class: "",//昵称
    form_phone_class: "",//手机号
    form_ages_class: "",//年龄
    form_position_class: "",//场上位置
    nickName:'',
    userName:'',
    phoneNum: '',
    phoneAutomatic:false,//显示自动获取
    phoneManual: true,//显示用户输入
    positionId:[],
    positionName: [],
    positionIndex: 0,
    session_key:'',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  
  onLoad: function () {
    var userInfo = wx.getStorageSync("userInfo");
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
      })
    } else {
      wx.reLaunch({
        url: '../authorize/authorize',
      })
    }
    var that = this;
    //获取场上位置
    wx.request({
      url: app.globalData.httpsPath + '/position', // 接口地址
      method: "POST",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        var posidArry = [];
        var posArry = [];
        var positionList = res.data.data;
        for (var i = 0; i < positionList.length; i++){
          posidArry.push(positionList[i].id);
          posArry.push(positionList[i].name);
        }
        that.setData({
          positionId: posidArry,
          positionName: posArry
        })
      }
    })
    
  },

  //获取用户输入的用户名
  userNameInput: function (e) {
    this.setData({
      userName: e.detail.value
    })
  },
  //获取用户输入的手机号
  phoneInput: function (e) {
    this.setData({
      phoneNum: e.detail.value
    })
  },
  //获取用户场上位置
  bindPickerChange(e) {
    this.setData({
      positionIndex: e.detail.value
    })
  },
  //获取用户手机号
  getPhoneNumber: function (e) {
    var that = this;
    console.info(e.detail.errMsg );
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny' || e.detail.errMsg == 'getPhoneNumber:user deny') {
      this.setData({
        phoneAutomatic:true,
        phoneManual:false
      });
    } else {
      var _iv = e.detail.iv;
      var _encryptedData = e.detail.encryptedData;
      wx.request({
        url: app.globalData.httpsPath + '/get-sessionkey', // 接口地址
        method: "POST",
        data: {
          code: wx.getStorageSync("codeId")
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if(res.data.status != false){
            var _key = res.data.data;
            that.setData({
              session_key: _key
            })
            wx.request({
              url: app.globalData.httpsPath + '/get-phone', // 接口地址
              method: "POST",
              data: {
                session_key: that.data.session_key,
                iv: _iv,
                encryptData: _encryptedData
              },
              header: {
                'content-type': 'application/json' // 默认值
              },
              success(res) {
                var phNum = res.data.data.phoneNumber;
                that.setData({
                  phoneNum : phNum
                })
              }
            })
          }
          
        }
      })

    }
  },

  //点击注册按钮进入首页
  registerBtn: function () {
    var that = this;
    var phone = that.data.phoneNum;
    var location = wx.getStorageSync("location");
    var _postionId = that.data.positionId;
    var _selected_id = _postionId[that.data.positionIndex];
    if (that.data.userName == '') {
      this.setData({
        form_name_class: "form-control-error"
      });
      wx.showToast({
        icon: "none",
        title: '请输入您的姓名'
      })
      return false;
    } 
    if (phone == '') {
      this.setData({
        form_phone_class: "form-control-error"
      });
      wx.showToast({
        icon: "none",
        title: '请输入您的手机号'
      })
      return false;
    }
    if (!phoneRexp.test(phone)) {
      wx.showToast({
        icon: "none",
        title: '手机号格式有误'
      })
      return false;
    }
    if (location == ""){
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
            wx.showModal({
              title: '是否授权当前位置',
              content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
              success: function (res) {
                if (res.cancel) {
                  console.info("授权失败返回数据");
                } else if (res.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      if (data.authSetting["scope.userLocation"] == true) {
                        //获取经纬度
                        wx.getLocation({
                          type: 'gcj02',
                          success: (res) => {
                            wx.setStorageSync('location', res)
                            // const latitude = res.latitude // 纬度
                            // const longitude = res.longitude // 经度
                          },
                        })
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 5000
                        })
                        
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'success',
                          duration: 5000
                        })
                      }
                    }
                  })
                }
              }
            });
          }
        }
      })
      
    }else{
      wx.login({
        success: function (res) {
          wx.setStorageSync('codeId', res.code);
          app.globalData.code_key = res.code;
          wx.request({
            url: app.globalData.httpsPath + '/get-openid', // 接口地址
            method: "POST",
            data: {
              code: wx.getStorageSync("codeId"),
              nickname: that.data.userInfo.nickName,
              avatar: that.data.userInfo.avatarUrl,
              name: that.data.userName,
              phone: that.data.phone,
              latitude: location.latitude,
              longitude: location.longitude,
              position_id: _selected_id,
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res) {
              wx.setStorageSync("token", res.data.data.token)
              app.globalData.session_key = res.data.data.token;
              wx.showToast({
                title: '注册成功',
                icon: 'succes',
                duration: 3000,
                mask: true
              })
              setTimeout(function () {
                wx.reLaunch({
                  url: '../index/index'
                })
              }, 3000)

            }
          })
        }
      });
      
    }
  },
  //点击跳过
  jumpovertbtn:function(){
    var that = this;
    var location = wx.getStorageSync("location");
    if (location == "") {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
            wx.showModal({
              title: '是否授权当前位置',
              content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
              success: function (res) {
                if (res.cancel) {
                  console.info("授权失败返回数据");
                } else if (res.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      console.log(data);
                      if (data.authSetting["scope.userLocation"] == true) {
                        //获取经纬度
                        wx.getLocation({
                          type: 'gcj02',
                          success: (res) => {
                            wx.setStorageSync('location', res)
                            // const latitude = res.latitude // 纬度
                            // const longitude = res.longitude // 经度
                          },
                        })
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 5000
                        })

                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'success',
                          duration: 5000
                        })
                      }
                    }
                  })
                }
              }
            });
          }
        }
      })

    } else {
      
      wx.login({
        success: function (res) {
          console.info(res.code)
          wx.setStorageSync('codeId', res.code);
          app.globalData.code_key = res.code;
          wx.request({
            url: app.globalData.httpsPath + '/get-openid', // 接口地址
            method: "POST",
            data: {
              code: wx.getStorageSync("codeId"),
              nickname: that.data.userInfo.nickName,
              avatar: that.data.userInfo.avatarUrl,
              name: '',
              phone: '',
              latitude: location.latitude,
              longitude: location.longitude,
              position_id: '',
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res) {
              console.info("token:"+res.data.data.token)
              wx.setStorageSync("token", res.data.data.token)
              app.globalData.session_key = res.data.data.token;
              wx.showToast({
                title: '注册成功',
                icon: 'succes',
                duration: 3000,
                mask: true
              })
              setTimeout(function () {
                wx.reLaunch({
                  url: '../index/index'
                })
              }, 3000)

            }
          })
        }
      });

    }
  }
  
})

